package com.cskaoyan.service.wx;

import com.cskaoyan.bean.*;
import com.cskaoyan.mapper.*;
import com.cskaoyan.model.admin.vo.BaseData;
import com.cskaoyan.model.vx.vo.MarketGoodsProductList;
import com.cskaoyan.model.vx.vo.*;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: ChenZhuqi
 * @Date: 2021/12/2 20:37
 * @Description:
 */
@Service
public class WxGoodsByChenServiceImpl implements WxGoodsByChenService {
    @Autowired
    MarketGoodsMapper goodsMapper;
    @Autowired
    MarketCategoryMapper categoryMapper;
    @Autowired
    MarketGoodsAttributeMapper goodsAttributeMapper;
    @Autowired
    MarketGrouponMapper grouponMapper;
    @Autowired
    MarketIssueMapper issueMapper;
    @Autowired
    MarketGoodsProductMapper goodsProductMapper;
    @Autowired
    MarketBrandMapper brandMapper;
    @Autowired
    MarketCommentMapper commentMapper;
    @Autowired
    MarketUserMapper userMapper;
    @Autowired
    MarketGoodsSpecificationMapper goodsSpecificationMapper;
    @Autowired
    MarketCollectMapper collectMapper;
    @Autowired
    MarketFootPrintMapper marketFootPrintMapper;

    @Override
    public int goodsCount() {

        MarketGoodsExample goodsExample = new MarketGoodsExample();

        long l = goodsMapper.countByExample(goodsExample);
        return (int) l;
    }

    @Override
    //传入的id是二级商品菜单，首页点击进入的是一级标签，需要判断
    public GoodsCategoryByChenVO goodsCategory(Integer id) {
        GoodsCategoryByChenVO goodsCategoryByChenVO = new GoodsCategoryByChenVO();
        MarketCategoryExample categoryExample = new MarketCategoryExample();
        //查出id的数据，方便得到各种字段
        MarketCategory marketCategory = categoryMapper.selectMarketCategoryById(id);
        if (marketCategory.getLevel().equals("L2")){//传入的id是二级商品菜单
            //得到它的pid
            Integer pid = marketCategory.getPid();
            //取出brotherCategory的参数，待更改
            categoryExample.createCriteria().andPidEqualTo(pid);
            List<MarketCategory> marketCategories = categoryMapper.selectByExample(categoryExample);
            //设置进入VO中
            goodsCategoryByChenVO.setBrotherCategory(marketCategories);
            //currentCategory的参数，是根据传入的id查出的 ，待更改
            MarketCategory marketCategory2 = categoryMapper.selectMarketCategoryById(id);
            //设置进入VO中
            goodsCategoryByChenVO.setCurrentCategory(marketCategory2);
            //parentCategory,完成
            MarketCategory marketCategory1 = categoryMapper.selectMarketCategoryById(pid);
            goodsCategoryByChenVO.setParentCategory(marketCategory1);
            return goodsCategoryByChenVO;
        }else {//首页点击进入的是一级标签

            //取出brotherCategory的参数，待更改
            categoryExample.createCriteria().andPidEqualTo(id);
            List<MarketCategory> marketCategories = categoryMapper.selectByExample(categoryExample);
            //设置进入VO中
            goodsCategoryByChenVO.setBrotherCategory(marketCategories);

            //currentCategory的参数，是根据传入的id查出的
            //1、先取出brotherCategory中的第一个标签的id
            Integer id1 = marketCategories.get(0).getId();
            //2、再设置入currentCategory
            MarketCategory marketCategory2 = categoryMapper.selectMarketCategoryById(id1);
            //设置进入VO中
            goodsCategoryByChenVO.setCurrentCategory(marketCategory2);

            //parentCategory,完成
            MarketCategory marketCategory1 = categoryMapper.selectMarketCategoryById(id);
            goodsCategoryByChenVO.setParentCategory(marketCategory1);
            return goodsCategoryByChenVO;

        }


    }

    @Override//传入的id是商品id 例子：1181000
    public GoodsDetailByChenVO goodsDetail(Integer id,Integer userId) {
        GoodsDetailByChenVO goodsDetailVO = new GoodsDetailByChenVO();
        //在goods表中，方便得到其他数据
        MarketGoods marketGoods = goodsMapper.selectByPrimaryKey(id);

        //attribute部分
        MarketGoodsAttributeExample goodsAttributeExample = new MarketGoodsAttributeExample();
        goodsAttributeExample.createCriteria().andGoodsIdEqualTo(id);
        List<MarketGoodsAttribute> goodsAttributes = goodsAttributeMapper.selectByExample(goodsAttributeExample);
        goodsDetailVO.setAttributes(goodsAttributes);


        //brand
        Integer brandId = marketGoods.getBrandId();
        MarketBrand marketBrand = brandMapper.selectByPrimaryKey(brandId);
        goodsDetailVO.setBrand(marketBrand);


        //comment-------------------------
       /* //统计出count（评论）的总数,valueid是商品id
        MarketMarketCommentExample commentExample = new MarketMarketCommentExample();
        commentExample.createCriteria().andValueIdEqualTo(id);
        long l = commentMapper.countByExample(commentExample);
        CommentByChenVO comment = new CommentByChenVO();
        comment.setCount(l);
        //找出data
        CommentInDetailVO commentInDetailVO = new CommentInDetailVO();
        //用于接收data
        List<CommentInDetailVO> data = new ArrayList<>();
        //通过该list找出data中所需要的数据
        List<MarketComment> marketComments = commentMapper.selectByExample(commentExample);
        //用于转换图片为数组
        MarketCommentList marketCommentList = new MarketCommentList();
        for (MarketComment marketComment : marketComments) {
            Integer userId = marketComment.getUserId();
            //-------------------------
            try {
                BeanUtils.copyProperties(marketCommentList, marketComment);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                String[] strings = objectMapper.readValue(marketComment.getPicUrls(), String[].class);
                marketCommentList.setPicUrls(strings);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            //-----------------------------------------
            //得到用户相关的信息
            MarketUser marketUser = userMapper.selectByPrimaryKey(userId);
            //对CommentInDetailVO进行set赋值
            commentInDetailVO.setUser(marketUser);
            commentInDetailVO.setComment(marketCommentList);
            //加到一个list中，之后将它赋值到CommentByChenVO中
            data.add(commentInDetailVO);
        }
        comment.setData(data);
        goodsDetailVO.setComment(comment);*/
        //comment

        GoodsDetailByChenVO goodsDetailCommentVO = new GoodsDetailByChenVO();

        MarketCommentExample commentExample = new MarketCommentExample();
        commentExample.createCriteria().andValueIdEqualTo(id);
        int count = (int) commentMapper.countByExample(commentExample);
        List<MarketComment> comments = commentMapper.selectByExample(commentExample);
        List<CommentInDetailVO> commentInDetailVO = new ArrayList<>();
        //用是string【】的MarketComment接收
        MarketCommentList marketCommentList = new MarketCommentList();
        for (MarketComment comment : comments) {
            MarketUser user = userMapper.selectByPrimaryKey(comment.getUserId());
            String picUrls = comment.getPicUrls();
            String[] picUrl = picUrls.replace("[", "").replace("]", "").split(",");


            /*try {
                BeanUtils.copyProperties(marketCommentList, comment);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                String[] strings = objectMapper.readValue(comment.getPicUrls(), String[].class);
                marketCommentList.setPicUrls(strings);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }


            marketCommentList.setPicUrls(picUrl);*/
            commentInDetailVO.add(new CommentInDetailVO(comment.getAddTime(), comment.getAdminContent(),
                    user.getAvatar(), comment.getContent(), comment.getId(), user.getNickname(), picUrl));
            if (commentInDetailVO.size()>3){
                break;
            }
        }
        CommentByChenVO commentByChenVO = new CommentByChenVO();
        commentByChenVO.setCount(count);
        commentByChenVO.setData(commentInDetailVO);
        goodsDetailVO.setComment(commentByChenVO);


        //groupon,暂时设置为null----------------------------
        List<MarketGroupon> objects = new ArrayList<>();
        goodsDetailVO.setGroupon(objects);


        // info，查询语句在上面，找marketGoods


        MarketGoodsList marketGoodsList = new MarketGoodsList();
        try {
            BeanUtils.copyProperties(marketGoodsList, marketGoods);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        ObjectMapper objectMapper = new ObjectMapper();
        try {
            String[] strings = objectMapper.readValue(marketGoods.getGallery(), String[].class);
            marketGoodsList.setGallery(strings);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        goodsDetailVO.setInfo(marketGoodsList);


        //issue
        MarketIssueExample marketIssueExample = new MarketIssueExample();
        List<MarketIssue> marketIssues = issueMapper.selectByExample(marketIssueExample);
        goodsDetailVO.setIssue(marketIssues);

        //productList
        MarketGoodsProductExample goodsProductExample = new MarketGoodsProductExample();
        goodsProductExample.createCriteria().andGoodsIdEqualTo(id);
        List<MarketGoodsProduct> goodsProducts = goodsProductMapper.selectByExample(goodsProductExample);
        //---------------
        MarketGoodsProductList marketList = new MarketGoodsProductList();
        List<MarketGoodsProductList> user2 = new ArrayList<>();
        for (MarketGoodsProduct user : goodsProducts) {
            try {
                BeanUtils.copyProperties(marketList, user);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
            ObjectMapper objectMapper1 = new ObjectMapper();
            try {
                String[] strings = objectMapper1.readValue(user.getSpecifications(), String[].class);
                marketList.setSpecifications(strings);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            user2.add(marketList);
        }
        //--------------
        goodsDetailVO.setProductList(user2);

        //share,暂时写成FALSE
        goodsDetailVO.setShare(false);
        //shareImage暂时写成空
        goodsDetailVO.setShareImage("");


        //specificationList
        MarketGoodsSpecificationExample goodsSpecificationExample = new MarketGoodsSpecificationExample();
        goodsSpecificationExample.setDistinct(true);
        goodsSpecificationExample.createCriteria().andGoodsIdEqualTo(id);
        //根据商品id找出所有的字段
        List<MarketGoodsSpecification> goodsSpecifications = goodsSpecificationMapper.selectByExample(goodsSpecificationExample);
        //赋值到specificationvoList中
        List<SpecificationVO> specificationVOS = new ArrayList<>();
        //在赋值之前先接收单独的每一个
        SpecificationVO specificationVO = new SpecificationVO();
        for (MarketGoodsSpecification goodsSpecification : goodsSpecifications) {
            //得到规格颜色之类的值
            goodsSpecificationExample.createCriteria().andSpecificationEqualTo(goodsSpecification.getSpecification());
            List<MarketGoodsSpecification> goodsSpecifications1 = goodsSpecificationMapper.selectByExample(goodsSpecificationExample);

            specificationVO.setName(goodsSpecification.getSpecification());
            specificationVO.setValueList(goodsSpecifications1);
            specificationVOS.add(specificationVO);
        }
        //最后赋值到goodsDetailVO中
        goodsDetailVO.setSpecificationList(specificationVOS);
        //userHasCollect
        MarketCollectExample collectExample = new MarketCollectExample();
        collectExample.createCriteria().andTypeEqualTo((byte) 0).andValueIdEqualTo(id);
        List<MarketCollect> marketCollects = collectMapper.selectByExample(collectExample);
        goodsDetailVO.setUserHasCollect(marketCollects.size());

        //加入历史足迹
        if(userId!=null){
            marketFootPrintMapper.insertMarketFootPrint(id, userId);
        }
        return goodsDetailVO;
    }

    @Override//传入的id为三级商品id 1116011
    public BaseData goodsRelated(Integer id) {
        BaseData data = new BaseData();
        data.setLimit(6);

        MarketGoodsExample goodsExample = new MarketGoodsExample();
        //先查询出该商品的所有字段
        MarketGoods marketGoods = goodsMapper.selectByPrimaryKey(id);
        //得到了二级商品id
        Integer categoryId = marketGoods.getCategoryId();
        //通过二级再去找其他的三级商品，
        goodsExample.createCriteria().andCategoryIdEqualTo(categoryId);
        // 得出全部三级商品
        PageHelper.startPage(1, data.getLimit());
        List<MarketGoods> marketGoods3 = goodsMapper.selectByExample(goodsExample);
        PageInfo<MarketGoods> pageInfo = new PageInfo<>(marketGoods3);
        int pages = pageInfo.getPages();
        long total = pageInfo.getTotal();

        return BaseData.list(marketGoods3, (int) total, 1, data.getLimit(), pages);
    }
}
